/*
 * Copyright the original author or authors.
 * 
 * Licensed under the MOZILLA PUBLIC LICENSE, Version 1.1 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *	  http://www.mozilla.org/MPL/MPL-1.1.html
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.googlecode.milib.tools {
	import com.googlecode.milib.base.MLBaseClass;

	/**
	 * @author Marek Brun
	 */
	public class MethodInvokeCache extends MLBaseClass {

		private var methodToCheckForCaching:Function;
		private var cachedArguments:Array;

		public function MethodInvokeCache(methodToCheckForCaching:Function=null) {
			this.methodToCheckForCaching=methodToCheckForCaching;
			cachedArguments=[];
		}
		
		/**
		 * @param args arguments class
		 * @return is true method call is cached, if false - not
		 */
		public function tryCacheMethodInvoke(args:*):Boolean {
			if(methodToCheckForCaching==null || methodToCheckForCaching()){
				cachedArguments.push(args);
				return true;
			}
			return false;
		}
		
		/**
		 * Invoke all cached methods, and clear
		 */
		public function flush():void {
			if(methodToCheckForCaching==null || methodToCheckForCaching()){
				throw new Error('Cant flush now. methodToCheckForCaching is return true');
			}
			var i:uint;
			var loopArgs:*;
			for(i=0;i<cachedArguments.length;i++){
				loopArgs=cachedArguments[i];
				loopArgs.callee.apply(null, loopArgs);
			}
		}
		
	}
}
